<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        
        <!-- jquery -->
        <script src="/lianxijs/libs/jquery/jquery-1.11.1.min.js"></script>
        
        <!-- http插件 -->
        <script src="/lianxijs/libs/http/axios.min.js"></script>
        
        <!-- 弹窗插件 -->
        <link rel="stylesheet" type="text/css" href="/lianxijs/libs/sweetalert/sweetalert.css"  />
        <script src="/lianxijs/libs/sweetalert/sweetalert-dev.js"></script>
        
        <!-- 时间格式化插件 -->
        <script src="/lianxijs/libs/moment/moment.min.js"></script>   
        
        <!-- 精确计算插件 -->
        <!-- <script src="/lianxijs/libs/number-precision/index.iife.js"></script> -->
        <script src="/lianxijs/libs/number-precision/index.umd.js"></script>
        
        <!-- 带搜索的下拉框 -->
        <link rel="stylesheet" type="text/css" href="/lianxijs/libs/select2/select2.css"/>
        <script src="/lianxijs/libs/select2/select2.js"></script>
        
        <!-- base64插件（https://github.com/dankogai/js-base64） -->
        <script src="/lianxijs/libs/base64/base64.min.js"></script>
        
    </head>
    <body>
        <div>
            <img src="/lianxijs/images/85010.jpg"/>
        </div>
        <br/>
        <div>
            <input type="button" value="转为base64" onClick="toBase64()"/>
        </div>
            <img id="img"/>
    </body>
</html>
<script>
    function toBase64() {
        console.log("aaaaaaaaaaaaa");
        urlToBase64("/images/85010.jpg", 'image/jpg').then(res => {
            console.log("bbbbbbbbbbbbb");
            $("#img").attr("src", res);
            // 转化后的base64图片地址
            //console.log('base64', res)
        })
    }
    // 原理： 利用canvas.toDataURL 的API转化成base64
    function urlToBase64(url, imageType) {
        if (!imageType) {
            imageType = "image/png";
        }
        return new Promise((resolve, reject) => {
            let image = new Image();
            image.onload = function () {
                let canvas = document.createElement('canvas');
                canvas.width = this.naturalWidth;
                canvas.height = this.naturalHeight;
                // 将图片插入画布并开始绘制
                canvas.getContext('2d').drawImage(image, 0, 0);
                // result
                let result = canvas.toDataURL(imageType);
                resolve(result);
            };
            // CORS 策略，会存在跨域问题https://stackoverflow.com/questions/20424279/canvas-todataurl-securityerror
            image.setAttribute("crossOrigin", "Anonymous");
            image.src = url;
            // 图片加载失败的错误处理
            image.onerror = () => {
                reject(new Error('图片流异常'));
            };
        });
    }
</script>